<template>
  <div>
    <el-space>
      <el-button type="success" :icon="Plus" @click="handleAdd">新增</el-button>
      <el-button type="primary" :icon="Refresh" @click="importAttrsData"
        >同步</el-button
      >
      <el-input
        v-model="searchParams.keyStr"
        placeholder="属性名称"
        style="margin-right: 10px"
        @keyup.enter="handleSearch"
      />
      <el-button type="primary" :icon="Search" @click="handleSearch"
        >搜索</el-button
      >
      <el-button :icon="Refresh" @click="reset">重置</el-button>
      <el-button
        type="danger"
        :icon="Delete"
        :disabled="selections.length == 0"
        @click="handleDelete"
        >删除</el-button
      >
      <el-button type="primary" @click="handleBatchEdit" :icon="EditPen"
        >批量修改</el-button
      >
    </el-space>
    <el-table
      v-loading="loading"
      bsort
      :data="attrsData"
      height="70vh"
      style="margin-top: 10px; min-height: 66vh"
      class="draggable"
      row-key="AttrId"
      @selection-change="handleRowSelect"
    >
      <el-table-column type="selection" />
      <el-table-column type="index" label="" />
      <el-table-column label="属性名称" prop="AttrName" />
      <el-table-column label="键名" prop="AttrKeyName" />
      <!-- <el-table-column
        width="300"
        label="属性值"
        prop="AttrValue"
        :formatter="formatterColumn"
      /> -->
      <el-table-column
        label="录入类型"
        prop="InputType"
        align="center"
        :formatter="formatterColumn"
      >
        <template v-slot="{ row }">
          <el-select
            v-model="row.InputType"
            :disabled="row.AttrKeyName == 'Settlement'"
            @change="handleChange(row)"
          >
            <el-option
              v-for="(item, key) in inputTypeMap"
              :key="key"
              :label="item"
              :value="Number(key)"
            >
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="默认值" prop="DefaultValue" />
      <el-table-column label="列表宽度" width="100" align="center">
        <template v-slot="{ row }">
          <el-input
            v-model="row.ColumnWidth"
            type="number"
            @change="handleChange(row)"
          ></el-input>
        </template>
      </el-table-column>
      <el-table-column label="列固定" width="150" align="center">
        <template v-slot="{ row }">
          <el-select v-model="row.FixType" @change="handleChange(row)">
            <el-option
              v-for="(item, key) in fixMap"
              :key="key"
              :label="item.label"
              :value="Number(key)"
            >
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column width="80" label="显示" align="center">
        <template v-slot="{ row }">
          <el-switch v-model="row.IsVisible" @change="handleChange(row)" />
        </template>
      </el-table-column>
      <el-table-column width="200" label="操作" align="center" fixed="right">
        <template v-slot="{ row }">
          <el-button link type="primary" @click="handleEdit(row)"
            >编辑</el-button
          >
          <!-- <el-button link type="primary">高级</el-button> -->
          <el-button link type="danger" @click="handleDelete(row.AttrId)"
            >删除</el-button
          >
        </template>
      </el-table-column>
      <!-- <el-table-column width="100" label="排序" prop="SortIndex" /> -->
      <el-table-column width="60" label="顺序">
        <el-popover
          placement="top-start"
          trigger="click"
          content="拖拽行进行调整顺序"
          teleported
        >
          <template #reference>
            <el-button
              link
              type="primary"
              :icon="Sort"
              class="drag-handler"
            ></el-button>
          </template>
        </el-popover>
      </el-table-column>
    </el-table>

    <pagination
      v-show="searchParams.total > 0"
      :total="searchParams.total"
      v-model:page="searchParams.pageNum"
      v-model:limit="searchParams.pageSize"
      @pagination="getData"
    />
    <DefaultEditModal
      :isUpdate="isUpdate"
      :open="openModal"
      :data="currentData"
      @closeModal="openModal = false"
      @reload="reload"
    />
    <DefaultBatchEditModal
      :open="openBatchModal"
      :data="currentData"
      @closeModal="openBatchModal = false"
      @reload="batchReload"
    />
  </div>
</template>
<script setup>
import { onMounted, reactive } from "vue";
import {
  Plus,
  Refresh,
  Search,
  Sort,
  Delete,
  EditPen,
} from "@element-plus/icons-vue";
import Sortable from "sortablejs";
import { createUniqueString } from "@/utils";
import { ElLoading, ElMessage, ElMessageBox } from "element-plus";
import DefaultEditModal from "./DefaultEditModal";
import DefaultBatchEditModal from "./DefaultBatchEditModal";
import useOrderAttrStore from "@/store/modules/orderAttrs";
import {
  fixMap,
  inputTypeMap,
  mainOrderCols,
  orderAttrsMap,
} from "../../../../../utils/map";
import { useRoute } from "vue-router";
import { deepClone } from "../../../../../utils";
import {
  attrQueryApi,
  attrUpdateApi,
  attrRemoveApi,
} from "@/api/order/attr/index.js";
import { mainAttrNames } from "@/utils/map.js";
let orderAttrStore = useOrderAttrStore();
const openModal = ref(false);
const openBatchModal = ref(false);
const isUpdate = ref(false);
const loading = ref(false);
const currentData = ref({});
const searchParams = ref({
  pageNum: 1,
  pageSize: 20,
  keyStr: "",
  total: 0,
  seriesId: 0,
});

const selections = ref([]);

function changePage(a, b, c) {
  // console.log('a,b,c', a, b, c)
}
// const attrsData = ref(
//   orderAttrStore.orderAttrs.find(
//     (item) => item.name == orderAttrStore.currentProductTabName
//   ).attrs
// );
// const attrsDataCopy = ref(deepClone(attrsData.value));
const attrsData = ref([]);
watch(
  () => orderAttrStore.currentProductSeries.SeriesId,
  (val) => {
    if (val && !searchParams.value.seriesId) {
      searchParams.value.seriesId =
        orderAttrStore.currentProductSeries.SeriesId;
      getData();
    }
  }
);
onMounted(async () => {
  //模拟网络请求
  searchParams.value.keyStr = orderAttrStore.attrSearchValue;
  await getData();
  rowDrag();
});
async function getData() {
  loading.value = true;
  searchParams.value.seriesId = orderAttrStore.currentProductSeries.SeriesId;
  if(searchParams.value.seriesId){
    const res = await attrQueryApi(searchParams.value);
    attrsData.value = res.Data;
    loading.value = false;
    searchParams.value.total = res.TotalCount;
  }
}

function handleEdit(row) {
  isUpdate.value = true;
  openModal.value = true;
  currentData.value = Object.assign({}, row);
}

function formatterColumn(row, column) {
  switch (column.property) {
    case "AttrValue":
      return Object.values(row[column.property]).join(",");
    case "InputType":
      return inputTypeMap[row[column.property]];
  }
}

function handleAdd() {
  isUpdate.value = false;
  openModal.value = true;
  currentData.value = {
    SeriesId: orderAttrStore.currentProductSeries.SeriesId,
  };
}

async function reload(data, update) {
  // searchParams.value.keyStr = "";
  const res = await attrUpdateApi(data);
  if (res.IsSuccess) {
    ElMessage.success(update ? "修改成功" : "新增成功");
    getData();
  }
}
// 行拖拽
const rowDrag = function () {
  // 要拖拽元素的父容器
  const tbody = document.querySelector(
    ".draggable .el-table__body-wrapper tbody"
  );
  if (!tbody) return;
  Sortable.create(tbody, {
    //  可被拖拽的子元素
    draggable: ".draggable .el-table__row",
    async onEnd(event) {
      let { oldIndex, newIndex } = event;
      if (
        oldIndex !== undefined &&
        newIndex !== undefined &&
        newIndex !== oldIndex
      ) {
        await attrUpdateApi({
          ...attrsData.value[oldIndex],
          SortIndex: attrsData.value[newIndex].SortIndex,
        });
        await attrUpdateApi({
          ...attrsData.value[newIndex],
          SortIndex: attrsData.value[oldIndex].SortIndex,
        });
        getData();
      }
    },
  });
};

function handleDelete(id) {
  ElMessageBox.confirm(
    selections.value.length
      ? `确认删除${selections.value.length}条数据？`
      : "确认删除？",
    "提示",
    {
      type: "warning",
    }
  )
    .then(async (res) => {
      if (searchParams.value.total > 1) {
        if (typeof id == "number") await attrRemoveApi([id]);
        else await attrRemoveApi(selections.value.map((e) => e.AttrId));
        ElMessage.success("删除成功");
        getData();
      } else {
        ElMessage.warning("至少保留一条数据");
      }
    })
    .catch((error) => {
      console.log(error);
    });
}

function handleSearch() {
  orderAttrStore.attrSearchValue = searchParams.value.keyStr
  getData();
}

function reset() {
  searchParams.value.keyStr = "";
  orderAttrStore.attrSearchValue = searchParams.value.keyStr
  getData();
}
function handleChangeOrderAttr(row, colName) {
  // 列固定、列宽等属性配置修改，其他产品系列保持一致
  orderAttrStore.orderAttrs.forEach((p) => {
    const attr = p.attrs.find((item) => item.attrName == row.attrName);
    if (attr) attr[colName] = row[colName];
  });
}
function handleRowSelect(e) {
  selections.value = e;
}
async function handleChange(row) {
  try {
    await attrUpdateApi(row);
    getData();
    ElMessage.success("修改成功");
  } catch (error) {
    ElMessage.error("修改失败:" + error);
  }
}
async function importAttrsData() {
  return;
  for (let i = 0; i < mainAttrNames.length; i++) {
    await attrUpdateApi({
      AttrName: mainAttrNames[i],
      InputType: 1,
      InputType2: 0,
      DefaultValue: "",
      ColumnWidth: 100,
      SortIndex: 0,
      IsVisible: true,
      FixType: 0,
      SeriesId: orderAttrStore.currentProductSeries.SeriesId,
    });
    ElMessage.success(`添加成功，${i + 1}/${mainAttrNames.length}`);
  }
}
function handleBatchEdit() {
  openBatchModal.value = true;
}
function batchReload() {
  getData();
  openBatchModal.value = false;
}
</script>
